package com.dabai.applicationmanager.ui.smallprogram;

import android.Manifest;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dabai.applicationmanager.R;
import com.dabai.applicationmanager.adapter.AppScanAdapter;
import com.dabai.applicationmanager.bean.AppScanBaseInfo;
import com.dabai.applicationmanager.dialog.MdcDialog;
import com.dabai.applicationmanager.dialog.TipAlertDialog;
import com.dabai.applicationmanager.impl.OnCompleteListener;
import com.dabai.applicationmanager.sort.ComparatorByLastModified;
import com.dabai.applicationmanager.utils.OtherUtils;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.AppUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.permissionx.guolindev.PermissionX;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import me.zhanghai.android.fastscroll.FastScrollerBuilder;

public class ReceiveFileActivity extends AppCompatActivity {

    Context context;
    private RecyclerView mRecyclerview;

    private AppScanAdapter appScanAdapter;
    private ArrayList<AppScanBaseInfo> appScanBaseInfo;
    private List<PackageInfo> packageInfo;
    private ArrayList<AppScanBaseInfo> appBaseInflows;

    private ArrayList<String> delList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_file);
        initViews();

        context = this;

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        PermissionX.init(this)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        DBToast.showText(context, "无储存权限，不能扫描外部目录。", false);
                        finish();
                    }
                });

        TipAlertDialog.init(context);

       mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
       mRecyclerview.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));

        new FastScrollerBuilder(mRecyclerview).build();

        queryFiles();

    }


    /**
     * 查询SD卡里安装包
     */
    private void queryFiles() {

        TipAlertDialog.getInstance(context).showTipLayout("正在扫描安装包...");

        new Thread(() -> {

            appScanBaseInfo = new ArrayList<>();
            delList = new ArrayList<>();

            List<File> fileArray = new ArrayList<>();

            // AppIconLoader appIconLoader = new AppIconLoader(130, true, context);
            PackageManager pm = context.getPackageManager();

            ArrayList<File> files = scanFilesWithSuffix(OtherUtils.getReceiveFileDirectory(context), "");

            Collections.sort(files, new ComparatorByLastModified(false));

            for (File file:files){

                String path = file.getAbsolutePath();

                PackageInfo info = pm.getPackageArchiveInfo(path, 0);

                if (info != null) {

                    //如果 minAPI比本机大  则不显示
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        if (Build.VERSION.SDK_INT < info.applicationInfo.minSdkVersion){
                            continue;
                        }
                    }

                    //添加到列表
                    fileArray.add(new File(path));

                    appScanBaseInfo.add(new AppScanBaseInfo(
                            AppUtils.isInstalled(context,info.packageName) ? "" : "未安装"
                            ,path
                            , getApkIcon(context,path)
                            , new File(path).getName()
                            , info.packageName,info.versionName+"("+info.versionCode+")"));

                    //已经安装的列表
                    if (AppUtils.isInstalled(context, info.packageName)) {
                        delList.add(path);
                    }

                }

            }


            //使用数据
            appScanAdapter = new AppScanAdapter(appScanBaseInfo, context);
            appScanAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);

            appScanAdapter.setOnItemClickListener((adapter, view, position) -> {

                //之前的单击事件
                AppScanBaseInfo appScanBaseInfo = (AppScanBaseInfo) adapter.getData().get(position);

                appBaseInflows = new ArrayList<>();
                appBaseInflows.add(appScanBaseInfo);

                OtherUtils.installApks(ReceiveFileActivity.this, appBaseInflows, new OnCompleteListener() {
                    @Override
                    public void start() {
                    }
                    @Override
                    public void complete() {
                    }

                    @Override
                    public void progress(int progress) {
                    }
                });

            });

            runOnUiThread(() -> {
                mRecyclerview.setAdapter(appScanAdapter);
                TipAlertDialog.getInstance(context).hideTipLayout();
                setTitle("接收的软件包(" + appScanAdapter.getData().size() + ")");
            });


        }).start();

    }



    public static Drawable getApkIcon(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            appInfo.sourceDir = apkPath;
            appInfo.publicSourceDir = apkPath;
            try {
                return appInfo.loadIcon(pm);
            } catch (OutOfMemoryError e) {
                Log.e("ApkIconLoader", e.toString());
            }
        }
        return null;
    }


    /**
     * 得到的文件后缀
     *
     * @param dir    dir
     * @param suffix 后缀
     */
    public ArrayList<File> scanFilesWithSuffix(@NonNull File dir,@NonNull String suffix){

        //储存文件
        ArrayList<File> fileList = new ArrayList<>();

        File[] files = dir.listFiles();

        for (File file:files){

            if (file.isFile()){
                if (file.getName().endsWith(suffix)){
                    fileList.add(file);
                }
            }else if (file.isDirectory()){
                scanDir(file,fileList,suffix);
            }
        }

        return fileList;
    }
    public void scanDir(File dir,ArrayList<File> fileList,@NonNull String suffix){
        File[] files = dir.listFiles();
        for (File file : files){
            if (file.isDirectory()){
                scanDir(file,fileList,suffix);
            }else {
                if (file.getName().endsWith(suffix)){
                    fileList.add(file);
                }
            }
        }
    }


    private void initViews() {
        mRecyclerview = findViewById(R.id.recyclerView);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        if (itemId == R.id.clean) {
            if (delList.size() <= 0 ){
                DBToast.showYellowToast(context,"没有需要清理的软件包!");
                return true;
            }

            MdcDialog.showConfirmDialog(context, "提示", "是否要删除已经安装的 " +delList.size()+" 个软件包?", new MdcDialog.OnConfirmDialogButtonListener() {
                @Override
                public void confirm() {

                    for (String path : delList){
                        FileUtils.delete(path);
                    }
                    DBToast.showText(context,"删除完成!",true);
                    queryFiles();

                }

                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);


            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.receive_files, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TipAlertDialog.destroyTipLayout();
    }

}